
#include "print_task_list.h"


static TaskHandle_t Task_Info_Search;
static TaskHandle_t Task_Info_Output;
static QueueHandle_t TaskList_Info_Queue;
char task_info_buffer[200] = {0};

static void showTaskInformation(void *args)
{
    BaseType_t  ret;
    UBaseType_t val;

    for (;;)
    {
        ret = xQueueReceive(TaskList_Info_Queue, task_info_buffer, portMAX_DELAY);
        if (ret != pdTRUE)
        {
            LOG("xQueueReceive failed! \r\n");
            continue;
        }

        LOG("tick:%d.]-----------------------------------------\r\n", xTaskGetTickCount());
        LOG("Name\t\tState\tPriority\tStack\tNum\r\n");
        LOG("%s\r\n", task_info_buffer);

        /* 查询系统历史剩余最小内存 */
        LOG("Total FreeRTOS memory size: %d bytes.\r\n", 
                        configTOTAL_HEAP_SIZE);    // 打印FreeRTOS总内存大小（单位字节）
                        
        LOG("The current remaining heap memory size is: %d bytes.\r\n", 
                        xPortGetFreeHeapSize());   // 查询当前剩余堆内存大小
                        
        LOG("Historical minimum remaining memory size: %d bytes.\r\n\r\n", 
                        xPortGetMinimumEverFreeHeapSize());     // 查询历史剩余最小内存大小

        /* 查询任务历史剩余最小内存  */
        val = uxTaskGetStackHighWaterMark(Task_Info_Search);
        
        LOG("Minimum historical remaining memory for the task: %d bytes\r\n ", 
                        (int)val * 4);

        vTaskDelay(2000);
    }

}


static void getTaskInformation(void *args)
{
  BaseType_t ret;
  char arr[200] = {0};
  char *ptr = NULL;

  ptr = pvPortMalloc(200);

  UNUSED(arr);
  UNUSED(ptr);

  for(;;)
  {
    vTaskList(task_info_buffer);
    ret = xQueueSend(TaskList_Info_Queue, 
                     (void *)task_info_buffer, 
                     (TickType_t)200);
    if (ret != pdTRUE)
    {
        LOG("xQueueReceive failed! \r\n");
        continue;
    }
    vTaskDelay(2000);
  }
}

void printTaskInit(void)
{
    /* 3.创建打印任务 */
    BaseType_t ret;

    TaskList_Info_Queue = xQueueCreate(1, 200);
    if (TaskList_Info_Queue == NULL)
    {
      LOG("xQueueCreate failed! \r\n");
      return;
    }

    ret = xTaskCreate(getTaskInformation,
                      "getTaskList",
                      256,
                      NULL,
                      2,
                      &Task_Info_Search);
    
    if (ret != pdPASS) {
      LOG("xTaskCreate [Task_Info_Search] failed! \r\n");
      return;
    }

    ret = xTaskCreate(showTaskInformation,
                      "logger",
                      256,
                      NULL,
                      2,
                      &Task_Info_Output);
    
    if (ret != pdPASS) {
      LOG("xTaskCreate [Task_Info_Search] failed! \r\n");
      return;
    }

    LOG("Task init O.K. \r\n");
    return;
}

